//
//  BaseUITableView.m
//  NovartisPPH
//
//  Created by Sidney on 13-9-26.
//  Copyright (c) 2013年 iSoftstone infomation Technology (Group) Co.,Ltd. All rights reserved.
//

#import "BaseUITableView.h"

static int loadMoreViewheight = 40;

#define LOADING_STATUS_INFO @"正在努力加载..."
#define PULL_DOWN_STATUS_INFO @"下拉进行刷新"
#define RELEASE_STATUS_INFO @"释放即可刷新"


@interface BaseUITableView()
{
    UIRefreshControl * refreshControl;
}

@property(nonatomic,assign)float curContentOffsetX;
@property(nonatomic,assign)float lastContentOffsetX;
@property(nonatomic,assign)float curContentOffsetY;
@property(nonatomic,assign)float lastContentOffsetY;

@property(nonatomic,strong)UIImageView * topLogoView;
//@property(nonatomic,strong)UILabel * lastUpdateTimeLabel;
@property(nonatomic,strong)UILabel * refreshTipLabel;
@property(nonatomic,strong)UIActivityIndicatorView * refreshindicator;

@end


@implementation BaseUITableView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        _curContentOffsetX = 0;
        _curContentOffsetY = 0;
    }
    return self;
}


- (void)addRefreshControl
{
//    refreshControl = [[UIRefreshControl alloc] init];
//    //    self.refreshControl.tintColor = [UIColor orangeColor];
//    [refreshControl addTarget:self action:@selector(doRefresh:) forControlEvents:UIControlEventValueChanged];
//    [refreshControl setAttributedTitle:[[NSAttributedString alloc] initWithString:@"下拉刷新"]];
//    [self addSubview:refreshControl];
    [self addRefreshFirstPageView];
}

- (void)doRefresh:(UIRefreshControl *)sender
{
    [refreshControl beginRefreshing];
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:LOADING_STATUS_INFO];

    if ([self.opetationDelegate respondsToSelector:@selector(tableViewRefreshFirstPage:)]) {
        [self.opetationDelegate tableViewRefreshFirstPage:self];
    }
//    [self performSelector:@selector(endRefreshing) withObject:nil afterDelay:3];
}

- (void)endRefreshing
{
//    [refreshControl setAttributedTitle:[[NSAttributedString alloc] initWithString:@"下拉刷新"]];
//    [refreshControl endRefreshing];
    [self stopRefreshFirstPage];
}

- (void)addReloadMoreDataBtn
{
    if (!_loadMoreBtn) {
        _loadMoreBtn = [[UIButton alloc] init];
        [_loadMoreBtn setTitle:@"向上滑动加载更多..." forState:UIControlStateNormal];
        [_loadMoreBtn setBackgroundColor:[UIColor clearColor]];
        [_loadMoreBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [_loadMoreBtn addTarget:self action:@selector(loadMoreBtnPressed) forControlEvents:UIControlEventTouchUpInside];
        _loadMoreBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        
        float height = loadMoreViewheight - 10 * 2;
        float width = CGRectGetWidth(self.frame) - 100;
        float originY = (loadMoreViewheight - height) / 2;
        float originX = (CGRectGetWidth(self.frame) - width) / 2;
        [_loadMoreBtn setFrame:CGRectMake(originX, originY, width, height)];
        
        _topLogoView = [[UIImageView alloc] init];
        _topLogoView.image = [UIImage imageNamed:@"image_top_2_logo"];
        [self addSubview:_topLogoView];
        
    }
    [self refreshLoadMoreBtnFrame];
    [self addSubview:_loadMoreBtn];
    _isLoadMore = YES;
}

- (void)refreshLoadMoreBtnFrame
{
    CGSize tempSize = self.contentSize;
    tempSize.height += loadMoreViewheight;
    self.contentSize = tempSize;
    float height = loadMoreViewheight - 10 * 2;
    float width = CGRectGetWidth(self.frame) - 100;
    float originY = (loadMoreViewheight - height) / 2 ;
    float originX = (CGRectGetWidth(self.frame) - width) / 2;
    [_loadMoreBtn setFrame:CGRectMake(originX, tempSize.height - originY - height, width, height)];
//    _topLogoView.frame = CGRectMake((CGRectGetWidth(self.frame) - 143) / 2,CGRectGetMaxY(_loadMoreBtn.frame) + 20, 143, 35);
}

- (void)removeReloadMoreDataBtn
{
    if (_isLoadMore) {
//        self.contentSize = CGSizeMake(CGRectGetWidth(self.frame), self.contentSize.height - loadMoreViewheight);
        [_loadMoreBtn removeFromSuperview];
        _loadMoreBtn = nil;
        _isLoadMore = NO;
    }
}

- (void)loadMoreBtnPressed
{
    if ([_opetationDelegate respondsToSelector:@selector(getMoreData:)]) {
        [_opetationDelegate getMoreData:self];
    }
}

- (void)refreshLastUpdateDate
{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yy-MM-dd HH:mm"];
//    _lastUpdateTimeLabel.text = [NSString stringWithFormat:@"最后更新:%@",[formatter stringFromDate:[NSDate date]]];
//    [[NSUserDefaults standardUserDefaults] setObject:_lastUpdateTimeLabel.text forKey:@"LastRefreshTime"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
    [_refreshindicator stopAnimating];
}


- (void)addRefreshFirstPageView
{
    _isRefreshfirstPage = YES;
    _isRefreshing = NO;
    if (!_refreshView) {
        float height = 70;
        float width = CGRectGetWidth(self.frame) - 30;
        float originY = -75;
        float originX = (CGRectGetWidth(self.frame) - width) / 2;
        
//        UIImageView * topLogo = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectGetWidth(self.frame) - 150) / 2,-150, 150, 70)];
//        topLogo.image = [UIImage imageNamed:@"image_top_1_logo"];
//        [self addSubview:topLogo];
        
        _refreshView = [[UIView alloc] initWithFrame:CGRectMake(originX, originY, width, height)];
        _refreshView.backgroundColor = [UIColor clearColor];
        
        _refreshTipLabel = [[UILabel alloc] initWithFrame:CGRectMake((width - 200) / 2, 30, 200, 30)];
        _refreshTipLabel.textColor = [UIColor darkGrayColor];
        _refreshTipLabel.backgroundColor = [UIColor clearColor];
        _refreshTipLabel.font = [UIFont boldSystemFontOfSize:13];
        _refreshTipLabel.text = PULL_DOWN_STATUS_INFO;
        _refreshTipLabel.textAlignment = NSTextAlignmentCenter;
        [_refreshView addSubview:_refreshTipLabel];
        
        
//        _lastUpdateTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake((width - 200) / 2, 30, 230, 40)];
//        _lastUpdateTimeLabel.backgroundColor = [UIColor clearColor];
//        _lastUpdateTimeLabel.textColor = [UIColor darkGrayColor];
//        _lastUpdateTimeLabel.font = [UIFont systemFontOfSize:14];
//        NSString * time = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastRefreshTime"];
//        
//        if (!time) {
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            [formatter setDateFormat:@"yy-MM-dd HH:mm"];
//            time = [NSString stringWithFormat:@"最后更新:%@",[formatter stringFromDate:[NSDate date]]];
//        }
//        
//        _lastUpdateTimeLabel.text = time;
//        _lastUpdateTimeLabel.textAlignment = NSTextAlignmentCenter;
//        [_refreshView addSubview:_lastUpdateTimeLabel];
        
        _refreshindicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _refreshindicator.center = CGPointMake(80 , 45);
        _refreshindicator.tintColor = MAIN_BLACK_COLOR;
        [_refreshindicator setHidesWhenStopped:YES];
        [_refreshView addSubview:_refreshindicator];
        
    }
    [self addSubview:_refreshView];
}

- (void)startRefreshFirstPage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
                         [self setContentInset:UIEdgeInsetsMake(70, 0, 0, 0)];
                         [_refreshindicator startAnimating];
                         _refreshTipLabel.text = LOADING_STATUS_INFO;
                         _isRefreshing = YES;
                         
                     }];
    if ([_opetationDelegate respondsToSelector:@selector(tableViewRefreshFirstPage:)]) {
        [_opetationDelegate tableViewRefreshFirstPage:self];
    }
//    [self performSelector:@selector(stopRefreshFirstPage) withObject:nil afterDelay:3];
}



- (void)stopRefreshFirstPage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
//                         [self setContentOffset:CGPointZero];
                         [self setContentInset:UIEdgeInsetsZero];
                         [self refreshLastUpdateDate];
                         _refreshTipLabel.text = PULL_DOWN_STATUS_INFO;
                         _isRefreshing = NO;
                         
                     } ];
}


- (void)removeRefreshFirstPageView
{
    [self stopRefreshFirstPage];
    _isRefreshfirstPage = NO;
    [_refreshView removeFromSuperview];
    _isRefreshing = NO;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_isRefreshfirstPage) {
        int offset = scrollView.contentOffset.y;
        
        if (![_refreshTipLabel.text isEqualToString:LOADING_STATUS_INFO]) {
            if (offset < -60) {
                _refreshTipLabel.text = RELEASE_STATUS_INFO;
            }else{
                _refreshTipLabel.text = PULL_DOWN_STATUS_INFO;
            }
        }
    }
    
    _lastContentOffsetX = _curContentOffsetX;
    _lastContentOffsetY = _curContentOffsetY;
    _curContentOffsetX = scrollView.contentOffset.x;
    _curContentOffsetY = scrollView.contentOffset.y;
    
    if (_curContentOffsetX > _lastContentOffsetX || _curContentOffsetY > _lastContentOffsetY) {
        _scrollDir = DOWN_RIGHT;
    }else if (_curContentOffsetX < _lastContentOffsetX || _curContentOffsetY < _lastContentOffsetY){
        _scrollDir = UP_LEFT;
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate) {
        float hight = scrollView.contentSize.height;
        float offsetY = (scrollView.contentOffset.y + CGRectGetHeight(self.frame));
        
        if (_isLoadMore) {
            if ((offsetY - hight > 40)) {
                [self loadMoreBtnPressed];
            }
        }
        if(_isRefreshfirstPage)
        {
            if (scrollView.contentOffset.y < -60){
                [self startRefreshFirstPage];
            }
        }
        
    }else{
        
        
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    return cell;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
